package com.lin.service;

import com.lin.dao.ArticleMapper;
import com.lin.pojo.Article;
import com.lin.util.CreateDate;
import com.lin.util.DealJson;
import com.lin.util.RandomID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName ArticleServiceImpl
 * @Description 文章功能的逻辑处理
 * @Author LinZePeng
 * @Date 2021/5/3 11:21
 * @Version 1.0
 */
@Service
public class ArticleServiceImpl implements ArticleService {

	@Autowired
	private ArticleMapper articleMapper;

	/**
	 * @Description 实现接口（查询所有文章）
	 * @Param []
	 * @return java.util.List<com.lin.pojo.Article>
	 */
	@Override
	public List<Article> queryArticle() {
		return articleMapper.queryArticle();
	}


	/**
	 * @Description 功能实现（添加文章）
	 * @Param [article]
	 * @return java.lang.Boolean
	 */
	@Override
	public Boolean addArticle(String article, HttpServletRequest httpServletRequest) {
		Cookie[] cookies = httpServletRequest.getCookies();
		String value = null;
		for (Cookie cookie : cookies) {
			if ("userID".equals(cookie.getName())){
				value=cookie.getValue();
			}
		}

		Article articleTo = (Article) DealJson.getObject(article, Article.class);
		assert articleTo != null;
		String num = RandomID.getRandomID();
		boolean aBoolean = false;
		if (articleMapper.queryByArtId(num) != null) {
			aBoolean=true;
		}
		while (aBoolean){
			num = RandomID.getRandomID();
			if (articleMapper.queryByArtId(num) != null) {
				aBoolean=false;
			}
		};
		articleTo.setArtID(num);
		articleTo.setUserID(value);
       //articleTo.setUserID("12");测试的话注释调上面的内容
		articleTo.setArtTime(CreateDate.getCreateDate());
		articleTo.setArtStatus(Integer.parseInt("1"));
		articleTo.setArtLikes(Integer.parseInt("2"));
		return articleMapper.addArticle(articleTo);
	}

	/**
	 * @Description 功能实现（查询artID是否存在）
	 * @Param [artId]
	 * @return java.lang.Boolean
	 */
	@Override
	public Boolean queryByArtId(String artId) {
		return articleMapper.queryByArtId(artId);
	}

	/**
	 * @Description 功能实现（查询comID是否存在）
	 * @Param [comId]
	 * @return java.lang.Boolean
	 */
	@Override
	public Boolean queryByComId(String comId) {
		return articleMapper.queryByArtId(comId);
	}


	/**
	 * @Description 功能实现（通过artTitle得到comID)
	 * @Param [artTitle]
	 * @return java.lang.String
	 */
	@Override
	public String queryByArtTitleGetComId(String artTitle) {
		return articleMapper.queryByArtTitleGetComId(artTitle);
	}

	@Override
	public Article queryByArtID(String artId) {
		return articleMapper.queryByArtID(artId);
	}
}
